import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/border_widget.dart';
import '../../function/states/team_conversation_state.dart';
import '../../function/states/private_conversation_state.dart';
import '../../function/states/user_state.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/toast_widget.dart';

/// 消息中心页面
class MessageCenterPage extends StatefulWidget {
  const MessageCenterPage({super.key});

  @override
  State<MessageCenterPage> createState() => _MessageCenterPageState();
}

class _MessageCenterPageState extends State<MessageCenterPage> {
  @override
  void initState() {
    super.initState();
    // 监听团队群聊状态变化
    TeamConversationState.teamGroupsBeacon.subscribe((teamGroups) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听私人对话状态变化
    PrivateConversationState.conversationMessagesBeacon.subscribe((messages) {
      if (mounted) {
        setState(() {});
      }
    });
    // 监听用户状态变化
    UserState.currentUserBeacon.subscribe((currentUser) {
      if (mounted) {
        setState(() {});
      }
    });
  }

  /// 格式化时间显示
  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${dateTime.month}/${dateTime.day}';
    } else if (difference.inHours > 0) {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } else {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    }
  }

  /// 显示清除所有未读消息的确认对话框
  void _showClearAllUnreadDialog() {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Container(
            decoration: BoxDecoration(
              color: const Color(0xFF663507),
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(color: const Color(0xFFFF8A3C), width: 1.w),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题栏
                Container(
                  padding: EdgeInsets.all(20.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFFF8A3C),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(16.r),
                      topRight: Radius.circular(16.r),
                    ),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.clear_all, color: Colors.white, size: 24.w),
                      SizedBox(width: 12.w),
                      Expanded(
                        child: Text('Clear')
                            .fontSize(18.sp)
                            .textColor(Colors.white)
                            .fontFamily(
                              GoogleFonts.roboto(
                                fontWeight: FontWeight.w700,
                              ).fontFamily,
                            )
                            .fontWeight(FontWeight.w700),
                      ),
                      GestureDetector(
                        onTap: () => Navigator.of(context).pop(),
                        child: Icon(
                          Icons.close,
                          color: Colors.white,
                          size: 24.w,
                        ),
                      ),
                    ],
                  ),
                ),

                // 内容区域
                Padding(
                  padding: EdgeInsets.all(20.w),
                  child: Column(
                    children: [
                      // 说明文字
                      Text(
                            'Are you sure you want to clear all unread messages? This action cannot be undone.',
                          )
                          .fontSize(14.sp)
                          .textColor(Colors.white.withOpacity(0.8))
                          .fontFamily(
                            GoogleFonts.quicksand(
                              fontWeight: FontWeight.w500,
                            ).fontFamily,
                          )
                          .fontWeight(FontWeight.w500)
                          .textAlignment(TextAlign.center),

                      SizedBox(height: 24.h),

                      // 按钮区域
                      Row(
                        children: [
                          // 取消按钮
                          Expanded(
                            child: GestureDetector(
                              onTap: () => Navigator.of(context).pop(),
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 12.h),
                                decoration: BoxDecoration(
                                  color: Colors.white.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(8.r),
                                  border: Border.all(
                                    color: Colors.white.withOpacity(0.2),
                                    width: 1.w,
                                  ),
                                ),
                                child: Text('Cancel')
                                    .fontSize(14.sp)
                                    .textColor(Colors.white)
                                    .fontWeight(FontWeight.w600)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w600,
                                      ).fontFamily,
                                    )
                                    .textAlignment(TextAlign.center),
                              ),
                            ),
                          ),

                          SizedBox(width: 12.w),

                          // 确认按钮
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                Navigator.of(context).pop();
                                _clearAllUnreadMessages();
                              },
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 12.h),
                                decoration: BoxDecoration(
                                  color: const Color(0xFFFF8A3C),
                                  borderRadius: BorderRadius.circular(8.r),
                                ),
                                child: Text('Clear All')
                                    .fontSize(14.sp)
                                    .textColor(Colors.white)
                                    .fontWeight(FontWeight.w600)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w600,
                                      ).fontFamily,
                                    )
                                    .textAlignment(TextAlign.center),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 清除所有未读消息
  void _clearAllUnreadMessages() {
    final currentUserId = UserState.getCurrentUserInfo()?.userId ?? '';

    // 获取所有对话伙伴
    final conversationPartners =
        PrivateConversationState.getConversationPartners(currentUserId);

    // 清除每个对话的未读消息
    for (final partnerId in conversationPartners) {
      PrivateConversationState.markAllMessagesAsRead(currentUserId, partnerId);
    }

    // 显示成功提示
    'All unread messages cleared successfully'.showSuccess();
  }

  /// 格式化群聊创建时间显示
  String _formatTeamCreateTime(DateTime dateTime) {
    return '${dateTime.year}/${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')}';
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = UserState.getCurrentUserInfo();
    final currentUserId = currentUser?.userId ?? '';

    return Scaffold(
      extendBody: true,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 应用头部
              _buildAppHeader(context),

              // 可滚动的内容区域
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 20.h),

                      // 已加入的团队群聊部分
                      _buildJoinedTeamsSection(context, currentUserId),

                      SizedBox(height: 20.h),

                      // 联系人部分
                      _buildContactSection(context, currentUserId),

                      SizedBox(height: 30.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建应用头部
  Widget _buildAppHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 左侧：返回按钮和标题
          Row(
            children: [
              GestureDetector(
                onTap: () => AppRouteManager.goBack(),
                child: Row(
                  children: [
                    Icon(Icons.chevron_left, color: Colors.white, size: 24.w),
                    SizedBox(width: 12.w),
                    Text('Message Center')
                        .fontSize(18.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w600)
                        .fontFamily(
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w700,
                          ).fontFamily,
                        ),
                  ],
                ),
              ),
            ],
          ),

          // 右侧：清除所有未读消息
          GestureDetector(
            onTap: _showClearAllUnreadDialog,
            child: Image.asset(
              'assets/images/clean.png',
              width: 32.w,
              height: 32.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建已加入的团队群聊部分
  Widget _buildJoinedTeamsSection(BuildContext context, String currentUserId) {
    final userTeams = TeamConversationState.getUserTeams(currentUserId);

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text('Joined Teams')
              .fontSize(24.sp)
              .textColor(const Color(0xFFFF8A3C))
              .fontWeight(FontWeight.w500)
              .fontFamily(
                GoogleFonts.rokkitt(fontWeight: FontWeight.w500).fontFamily,
              ),

          SizedBox(height: 16.h),

          // 团队群聊列表
          if (userTeams.isNotEmpty)
            ...userTeams.asMap().entries.map((entry) {
              final index = entry.key;
              final team = entry.value;
              final isLast = index == userTeams.length - 1;
              return _buildTeamCard(context, team, isLast);
            })
          else
            _buildEmptyTeamsCard(),
        ],
      ),
    );
  }

  /// 构建团队卡片
  Widget _buildTeamCard(BuildContext context, dynamic team, bool isLast) {
    final creatorInfo = TeamConversationState.getUserInfo(team.creatorId);
    final creatorAvatar =
        creatorInfo?['userAvatar'] ?? 'assets/images/avatar1.png';

    return GestureDetector(
      onTap: () {
        AppRouteManager.navigateToConversationChat(
          chatType: 'team',
          chatId: team.groupId,
          chatTitle: team.groupName,
        );
      },
      child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [const Color(0xFF854C14), const Color(0xFF853712)],
              ),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                // 团队封面图 - 超出容器
                Positioned(
                  left: 12.w,
                  bottom: 8.h,
                  child: SizedBox(
                    width: 72.w,
                    height: 80.w,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.r),
                        image: DecorationImage(
                          image: AssetImage(team.groupCoverImage),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ),
                ),

                // 主要内容区域
                Padding(
                  padding: EdgeInsets.fromLTRB(
                    90.w,
                    10.h,
                    12.w,
                    10.h,
                  ), // 左侧为封面图留空间，其他保持padding
                  child: Row(
                    children: [
                      // 团队信息
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 地点信息
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  'assets/images/location.png',
                                  width: 16.w,
                                  height: 16.w,
                                ),
                                SizedBox(width: 8.w),
                                Expanded(
                                  child: Text(
                                        team.location,
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      )
                                      .fontSize(12.sp)
                                      .textColor(Colors.white)
                                      .fontWeight(FontWeight.w500)
                                      .fontFamily(
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w500,
                                        ).fontFamily,
                                      ),
                                ),
                              ],
                            ),

                            SizedBox(height: 4.h),

                            // 创建时间
                            Row(
                              children: [
                                Image.asset(
                                  'assets/images/time.png',
                                  width: 16.w,
                                  height: 16.w,
                                ),
                                SizedBox(width: 8.w),
                                Text(_formatTeamCreateTime(team.createTime))
                                    .fontSize(12.sp)
                                    .textColor(Colors.white)
                                    .fontWeight(FontWeight.w500)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w500,
                                      ).fontFamily,
                                    ),
                              ],
                            ),
                          ],
                        ),
                      ),

                      // 创建人头像和聊天按钮
                      Row(
                        children: [
                          // 创建人头像
                          Container(
                            width: 32.w,
                            height: 32.w,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              image: DecorationImage(
                                image: AssetImage(creatorAvatar),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),

                          SizedBox(width: 8.w),

                          // 聊天按钮
                          Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 8.w,
                              vertical: 6.h,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(36.r),
                            ),
                            child: Text('Chat')
                                .fontSize(13.sp)
                                .textColor(const Color(0xFFFF8A3C))
                                .fontWeight(FontWeight.w600)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w600,
                                  ).fontFamily,
                                ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )
          .configBorderWidget(
            borderRadius: 8.r,
            borderColor: Colors.white,
            borderWidth: 1.w,
          )
          .paddingBottom(isLast ? 0 : 20.h),
    );
  }

  /// 构建空团队卡片
  Widget _buildEmptyTeamsCard() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            const Color(0xFFFF8A3C).withOpacity(0.1),
            const Color(0xFFFF8A3C).withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1.w),
      ),
      child: Center(
        child: Text('No teams joined yet')
            .fontSize(16.sp)
            .textColor(Colors.white.withOpacity(0.7))
            .fontWeight(FontWeight.w500)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w500).fontFamily,
            ),
      ),
    );
  }

  /// 构建联系人部分
  Widget _buildContactSection(BuildContext context, String currentUserId) {
    final conversationPartners =
        PrivateConversationState.getConversationPartners(currentUserId);

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text('Contact')
              .fontSize(24.sp)
              .textColor(const Color(0xFFFF8A3C))
              .fontWeight(FontWeight.w500)
              .fontFamily(
                GoogleFonts.rokkitt(fontWeight: FontWeight.w500).fontFamily,
              ),

          SizedBox(height: 12.h),

          // 联系人列表
          if (conversationPartners.isNotEmpty)
            ...conversationPartners.asMap().entries.map((entry) {
              final index = entry.key;
              final partnerId = entry.value;
              final isLast = index == conversationPartners.length - 1;
              return _buildContactCard(
                context,
                partnerId,
                currentUserId,
                isLast,
              );
            })
          else
            _buildEmptyContactsCard(),
        ],
      ),
    );
  }

  /// 构建联系人卡片
  Widget _buildContactCard(
    BuildContext context,
    String partnerId,
    String currentUserId,
    bool isLast,
  ) {
    final userInfo = PrivateConversationState.getUserInfo(partnerId);
    final userName = userInfo?['userName'] ?? 'Unknown User';
    final userAvatar = userInfo?['userAvatar'] ?? 'assets/images/avatar1.png';
    final lastMessage = PrivateConversationState.getLastMessageWithUser(
      currentUserId,
      partnerId,
    );

    return GestureDetector(
          onTap: () {
            AppRouteManager.navigateToConversationChat(
              chatType: 'private',
              chatId: partnerId,
              chatTitle: userName,
            );
          },
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 13.h),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [const Color(0xFF854D14), const Color(0xFF852C12)],
              ),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child: Row(
              children: [
                // 用户头像
                Container(
                  width: 48.w,
                  height: 48.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    image: DecorationImage(
                      image: AssetImage(userAvatar),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),

                SizedBox(width: 12.w),

                // 用户信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 用户名
                      Text(userName)
                          .fontSize(16.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w600)
                          .fontFamily(
                            GoogleFonts.quicksand(
                              fontWeight: FontWeight.w600,
                            ).fontFamily,
                          ),

                      SizedBox(height: 4.h),

                      // 最后一条消息预览
                      if (lastMessage != null)
                        Text(
                              lastMessage.content.length > 30
                                  ? '${lastMessage.content.substring(0, 30)}...'
                                  : lastMessage.content,
                            )
                            .fontSize(12.sp)
                            .textColor(Colors.white)
                            .fontWeight(FontWeight.w400)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                            )
                      else
                        Text('No messages yet')
                            .fontSize(14.sp)
                            .textColor(Colors.white.withOpacity(0.6))
                            .fontWeight(FontWeight.w400)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w400,
                              ).fontFamily,
                            ),
                    ],
                  ),
                ),

                // 时间和未读消息数
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    // 时间
                    if (lastMessage != null)
                      Text(_formatTime(lastMessage.sendTime))
                          .fontSize(13.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w400)
                          .fontFamily(
                            GoogleFonts.quicksand(
                              fontWeight: FontWeight.w400,
                            ).fontFamily,
                          ),

                    SizedBox(height: 4.h),

                    // 未读消息数
                    _buildUnreadCountBadge(currentUserId, partnerId),
                  ],
                ),
              ],
            ),
          ),
        )
        .configBorderWidget(
          borderRadius: 16.r,
          borderColor: Colors.white,
          borderWidth: 1.w,
        )
        .paddingBottom(isLast ? 0 : 20.h);
  }

  /// 构建未读消息数徽章
  Widget _buildUnreadCountBadge(String currentUserId, String partnerId) {
    // 获取与特定用户的未读消息数量
    final conversation = PrivateConversationState.getConversationBetweenUsers(
      currentUserId,
      partnerId,
    );
    final unreadCount =
        conversation
            .where(
              (message) =>
                  message.senderId == partnerId &&
                  message.receiverId == currentUserId &&
                  !message.isRead,
            )
            .length;

    if (unreadCount > 0) {
      // 有未读消息，显示红色徽章
      return Container(
        constraints: BoxConstraints(minWidth: 20.w),
        height: 20.h,
        padding: EdgeInsets.symmetric(horizontal: 6.w),
        decoration: BoxDecoration(
          color: const Color(0xFFFF8A3C),
          borderRadius: BorderRadius.circular(10.r),
        ),
        child: Center(
          child: Text(unreadCount > 99 ? '99+' : unreadCount.toString())
              .fontSize(12.sp)
              .textColor(Colors.white)
              .fontWeight(FontWeight.w600)
              .fontFamily(
                GoogleFonts.quicksand(fontWeight: FontWeight.w600).fontFamily,
              ),
        ),
      );
    } else {
      // 没有未读消息，显示占位符
      return Container(
        width: 20.w,
        height: 20.h,
        // 透明占位符，保持布局一致
      );
    }
  }

  /// 构建空联系人卡片
  Widget _buildEmptyContactsCard() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            const Color(0xFFFF8A3C).withOpacity(0.1),
            const Color(0xFFFF8A3C).withOpacity(0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1.w),
      ),
      child: Center(
        child: Text('No conversations yet')
            .fontSize(16.sp)
            .textColor(Colors.white.withOpacity(0.7))
            .fontWeight(FontWeight.w500)
            .fontFamily(
              GoogleFonts.quicksand(fontWeight: FontWeight.w500).fontFamily,
            ),
      ),
    );
  }
}
